package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.config.RuoYiConfig;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.BooleanMessage;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SendSmsService;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SessionLoginUser;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysUserServiceImpl UserService;

    @Autowired
    private SysDeptServiceImpl sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SendSmsService sendSmsService;
    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody, HttpServletRequest request)
    {
        AjaxResult ajax = success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        SysUser loginuser = UserService.selectUserByLoginName(loginBody.getUsername());
        try
        {
            // 登录成功 查询用户类型及单位信息  增加session信息
            SysUser mmOne = UserService.selectUserById(loginuser.getUserId());
            HttpSession session = request.getSession();
            SessionLoginUser mmloginuser= new SessionLoginUser();
            if(mmOne!=null){
                if(!"0".equals(mmOne.getStatus())){
                    return error("用户状态有误 登录失败");
                }
                // 查询单位信息
                SysDept mm登录单位 = sysDeptService.selectDeptById(mmOne.getDeptId());
                if(mm登录单位==null){
                    return error("单位信息有误 登录失败");
                }else if(!"0".equals(mm登录单位.getStatus())){
                    return error("单位状态有误 登录失败");
                }

                // 存储用户对象
                mmloginuser.setLoginName(mmOne.getUserName());
                mmloginuser.setLoginDeptId(mmOne.getDeptId().toString());
                mmloginuser.setLoginUserId(mmOne.getUserId().toString());
                SysDept Dept = sysDeptService.selectDeptById(mmOne.getDeptId()); // 查询单位信息
                mmloginuser.setLoginDeptName(Dept.getDeptName());
                session.setAttribute("iscunchu",1);  // 是否存在登录信息
                session.setAttribute("sessionlogin",mmloginuser); // 存入login信息
            }
            ajax.put(Constants.TOKEN, token);

            session.setMaxInactiveInterval(30 * 60);
            return ajax;
        }
        catch (Exception e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
        /*ajax.put(Constants.TOKEN, token);
        return ajax;*/
    }


    @PostMapping("/phonelogin")
    public AjaxResult phonelogin(@RequestBody LoginBody loginBody, HttpServletRequest request)
    {
        AjaxResult ajax = success();
        try
        {
          boolean 账户密码是否正确 = loginService.phonelogin(loginBody.getUsername(),loginBody.getPassword(),loginBody.getCode(),loginBody.getUuid());
          if(账户密码是否正确){
              // 账户密码正确 获得短信验证码
              //SysUser mm查询条件 = new SysUser();
              SysUser mm登录账户 = sysUserService.selectUserByLoginName(loginBody.getUsername());
              if(mm登录账户==null){
                  return error("用户或密码错误");
              }
              // 获得手机号 和生成验证码
              String phone  = mm登录账户.getPhonenumber();
              // 获得手机号 查询短信发送记录
              String phoneKey = CacheConstants.CAPTCHA_PHONE_KEY + phone;
              Object mm短信发送记录 = redisCache.getCacheObject(phoneKey);
              if(mm短信发送记录!=null){
                  return error("请勿重复发送短信验证码");
              }
              // 发送短信 和获得uuid
              BooleanMessage 短信发送 = getPhoneCode(phone);
              if(短信发送.isOk()){
                  return ajax.put("uuid",短信发送.getMessage());
              }else{
                  return error("短信发送失败");
              }

          }else{
              return error("用户或密码错误");
          }
        }
        catch (Exception e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
        /*ajax.put(Constants.TOKEN, token);
        return ajax;*/
    }

    // 获取账户密码 需要先传进来账户密码和验证码

    public BooleanMessage getPhoneCode(String Phone) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_PHONE_KEY + uuid;
        String phoneKey = CacheConstants.CAPTCHA_PHONE_KEY + Phone;
        String capStr = null,
                code = null;

        // 生成验证码
        Random random = new Random();
        int randomNumber = random.nextInt(89999) + 10000;
        code = randomNumber+""; // 更改为四位随机数

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES); // 存入验证码 有效期两分钟
        // 删除图片输出 改为发短信
        String 内容 = "您好  您的短信验证码是："+code;
        // 测试 不真的发
        BooleanMessage 结果 = sendSmsService.send短信Post(Phone,内容);
        redisCache.setCacheObject(phoneKey,"1111",Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);  // 存入短信号码 防止重复发送
        if(结果.isOk()){
            return BooleanMessage.getSuccessMessage(uuid);
        }else{
            return BooleanMessage.getErrorMessage("");
        }
    }


    @GetMapping("/ceshi")
    public String ceshi()
    {
        return "ceshiceshi";
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return success(menuService.buildMenus(menus));
    }
}
